// pages/citySearch/citySearch.js

import throttle from '../../utils/throttle.js';
import { scrollToLeftEnd } from '../../utils/behavior';

const app = getApp();
// 滚动高度
let scrollTopInside = 0;
let scrollTopInsideOversea = 0;
// switch底部距离页面顶部高度
// 后面滚动区域有所修改，可以认为是scroll-view顶部距离屏幕顶部的高度
let switchBottom;

// city-bar-item据顶部高度
let barToTop;
let barToTopOversea;

// 每个索引bar的高度
let itemHeight;

// 是否正在修改input内的值
let changeInputValue = false;
Page({
    behaviors: [scrollToLeftEnd],
    /**
     * 页面的初始数据
     */
    data: {
        scrollTop: 0,
        scrollTopOversea: 0,
        // 右侧激活的首字母索引
        activeAnchorIndex: null,
        activeAnchorIndexOversea: null,
        // 登陆弹窗
        showLoginCover: false,
        //外部人员弹窗
        powerTipCover: false,
        isFocus: false,
        isCancel: true,
        // 输入框内容
        inputValue: '',
        tabsArr: ['国内', '国际/港澳台'],
        currentTabIndex: 0,
        //轮播窗口高度
        swiperHeight: '',
        // 当前城市
        currentCity: {
            country: '中国',
            city: '北京',
            location: {
                lat: 39.90469,
                lng: 116.40717,
            },
        },
        // 历史城市
        historyCityArr: [],
        // 当前和历史城市
        curAndHistoryArr: [],
        overseaAndHistoryArr: [],
        // 热门城市
        hotCityArr: [],
        // 海外热门城市
        hotCityArrOversea: [],
        // 所有的城市列表
        allCityObject: {},
        allCityObjectOversea: {},
        // 有记录的城市数组
        recordCityArr: [],
        recordCityArrOversea: [],
        // 右侧索引数组
        indexList: [],
        indexListOversea: [],
        // 模糊匹配的城市
        matchCity: [],
        // 有匹配
        match: true,
        // 正在搜索
        searching: false,
        // 城市列表数据类型 datapoint录入数据点  specialpoint网络特殊点  checkin测试打卡数 默认打卡数
        sortRulesArr: [
            {
                cityListType: 'checkin',
                cityListTypeText: '测试打卡数',
            },
            {
                cityListType: 'datapoint',
                cityListTypeText: '录入数据点',
            },
            {
                cityListType: 'specialpoint',
                cityListTypeText: '网络特殊点',
            },
        ],
        // 当前排序规则索引
        currentSortRuleIndex: 0,
        // 当前排序规则索引海外
        currentSortRuleIndexOversea: 0,
        // 我的城市数目
        myCityCount: 0,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            curAndHistoryArr: wx.getStorageSync('cur_and_history') || [],
            overseaAndHistoryArr: wx.getStorageSync('cur_and_seahistory') || [],
            hotCityArr: wx.getStorageSync('hot_cites') || [],
            recordCityArr: wx.getStorageSync('record_cites') || [],
            indexList: wx.getStorageSync('index_list') || [],
            hotCityArrOversea: wx.getStorageSync('hot_cites_oversea') || [],
            recordCityArrOversea:
                wx.getStorageSync('record_cites_oversea') || [],
            indexListOversea: wx.getStorageSync('index_list_oversea') || [],
            currentTabIndex: app.globalData.countryBack === '中国' ? 0 : 1,
        });

        // 获取历史记录
        this.getCityHistory(
            app.globalData.authId,
            options.lat,
            options.lng,
            '00'
        );
        this.getseaCityHistory(
            app.globalData.authId,
            options.lat,
            options.lng,
            '01'
        );

        // 先获取国内/国际热门城市
        // this.getHotCities('00', 'hotCityArr');
        // this.getHotCities('01', 'hotCityArrOversea');

        // 获取有数据城市列表
        this.getCityInitialList(
            '00',
            'allCityObject',
            'recordCityArr',
            'indexList',
            this.data.currentSortRuleIndex
        );
        this.getCityInitialList(
            '01',
            'allCityObjectOversea',
            'recordCityArrOversea',
            'indexListOversea',
            this.data.currentSortRuleIndexOversea
        );

        this.setData({
            currentCity: {
                country: app.globalData.countryTap,
                city: app.globalData.addressTap,
                location: {
                    lat: options.lat,
                    lng: options.lng,
                },
            },
        });
        // 获取我的城市
        this.getMyCity();

        var that = this;
        //  高度自适应
        wx.getSystemInfo({
            success: function (res) {
                let clientHeight = res.windowHeight,
                    clientWidth = res.windowWidth,
                    rpxR = 750 / clientWidth,
                    swiperHeight;
                swiperHeight = clientHeight * rpxR - 172;
                that.setData({
                    swiperHeight: swiperHeight,
                });
            },
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let _that = this;
        if (!app.globalData.authId) {
            _that.setData({
                showLoginCover: true,
            });
        }
        if (app.globalData.authority == '07' || !app.globalData.authority) {
            _that.setData({
                powerTipCover: true,
            });
        }
        // 重置
        scrollTopInside = 0;
        scrollTopInsideOversea = 0;
    },

    onUnload() {
        console.log('缓存数据');
        let _that = this;
        // 当前及历史
        wx.setStorageSync('cur_and_history', _that.data.curAndHistoryArr);
        wx.setStorageSync(
            'cur_and_seahistory',
            _that.data.overseaAndHistoryArr
        );

        wx.setStorageSync('hot_cites', _that.data.hotCityArr);
        wx.setStorageSync('record_cites', _that.data.recordCityArr);
        wx.setStorageSync('index_list', _that.data.indexList);
        // 海外
        wx.setStorageSync('hot_cites_oversea', _that.data.hotCityArrOversea);
        wx.setStorageSync(
            'record_cites_oversea',
            _that.data.recordCityArrOversea
        );
        wx.setStorageSync('index_list_oversea', _that.data.indexListOversea);
    },

    // 监听input输入
    bindKeyInput: throttle(
        function (e) {
            if (changeInputValue) return;
            this.setData(
                {
                    inputValue: e.detail.value,
                    matchCity: [],
                },
                () => {
                    this.searchCities(e.detail.value);
                }
            );
        },
        1000,
        {
            trailing: false,
        }
    ),

    clear() {
        changeInputValue = true;
        this.setData({
            isCancel: true,
            inputValue: '',
        });
    },

    // focus事件
    focus() {
        changeInputValue = false;
        this.setData({
            isCancel: false,
            isFocus: true,
        });
    },

    blur() {
        this.setData({
            isFocus: false,
        });
    },
    onTabsClick(e) {
        this.setData({
            currentTabIndex: e.detail.index,
        });
        this.clear();
    },

    swiperChange(e) {
        this.setData({
            currentTabIndex: e.detail.current,
        });
        this.clear();
    },
    goToIndex(e) {
        let _that = this;
        if (_that.data.powerTipCover) {
            wx.showToast({
                title: '尚未登录，不可以切换城市',
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 2000,
            });
            return;
        }
        let country = e.currentTarget.dataset.country;
        let city = e.currentTarget.dataset.city;

        let lng = e.currentTarget.dataset.lng;
        let lat = e.currentTarget.dataset.lat;
        // 有些城市后台暂时没有经纬度
        if (lng && lat) {
            // 修改全局变量
            app.globalData.countryBack = country;
            app.globalData.addressBack = city;
            app.globalData.cityLat = lat;
            app.globalData.cityLng = lng;
            // 创建历史记录
            _that.createCitySearchHistory(app.globalData.authId, city, country);

            let pages = getCurrentPages(); //当前页面栈
            let prevPage = pages[pages.length - 2]; //上一页面
            prevPage.setData({
                //直接给index页面赋值
                mapLongitude: lng,
                mapLatitude: lat,
                mapScale: 12,
                choiceMappointValue: '全部类型', //显示切换地图点btn
                choiceType: '00',
            });
            wx.navigateBack({
                detal: 1,
            });
        } else {
            wx.showModal({
                title: '位置获取失败',
                content: '当前城市暂未覆盖，请联系后台管理员',
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        _that.clear();
                    }
                },
            });
        }
    },
    getPhoneNumber: function (e) {
        console.log(app.globalData.session_key);
        var _that = this;
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
            wx.request({
                url: app.globalData.rootPath + 'code/decryptUserData',
                data: {
                    encryptData: e.detail.encryptedData,
                    sessionKey: app.globalData.session_key,
                    iv: e.detail.iv,
                },
                method: 'GET',
                success: function (res) {
                    _that.setData({
                        phone: JSON.parse(res.data.resultStr).phoneNumber,
                    });
                    wx.setStorageSync('loginPhone', _that.data.phone);
                    console.log(_that.data.phone);
                    wx.request({
                        url: app.globalData.rootPath + 'code/login',
                        data: {
                            phone: _that.data.phone,
                        },
                        method: 'GET',
                        success: function (res) {
                            console.log(res);
                            app.globalData.authId = res.data.authId;
                            app.globalData.authority = res.data.authority;
                            app.globalData.realname = res.data.realname;
                            app.globalData.otherauthority =
                                res.data.otherauthority;
                            app.globalData.realpicurl = res.data.realnapicurl;
                            app.globalData.localcityTeam = res.data.localcity;
                            _that.setData({
                                showLoginCover: false,
                            });
                            setTimeout(function () {
                                wx.showLoading({
                                    title: '登录中',
                                });
                                wx.hideLoading();
                            }, 100);
                            let pages = getCurrentPages(); //当前页面栈
                            let prevPage = pages[pages.length - 2]; //上一页面
                            if (app.globalData.authority == '07') {
                                _that.setData({
                                    powerTipCover: true,
                                });
                                _that.powerTip();
                            }
                            prevPage.setData({
                                //直接给index页面赋值
                                showLoginCover: false,
                            });

                            // 重新获取历史记录
                            _that.getCityHistory(
                                app.globalData.authId,
                                _that.data.currentCity.location.lat,
                                _that.data.currentCity.location.lng,
                                '00'
                            );
                            _that.getseaCityHistory(
                                app.globalData.authId,
                                options.lat,
                                options.lng,
                                '01'
                            );
                            // 重新获取我的城市
                            _that.getMyCity();
                        },
                        fail: function (res) {
                            console.log(res);
                        },
                    });
                },
            });
        }
    },
    // 外部人员提示弹窗
    powerTip() {
        wx.showModal({
            title: '登录失败',
            content: '你还没有登录权限哦',
            showCancel: false,
            success: function (res) {},
        });
    },
    onBarTouchMove(e) {
        if (e.currentTarget.dataset.oversea == '00') {
            const sidebarLength = this.data.indexList.length;
            const touch = e.touches[0];
            console.log(touch.clientY, barToTop);
            let index = Math.floor((touch.clientY - barToTop) / itemHeight);
            if (index < 0) {
                index = 0;
            } else if (index > sidebarLength - 1) {
                index = sidebarLength - 1;
            }
            this.scrollToAnchor(index);
        } else if (e.currentTarget.dataset.oversea == '01') {
            const sidebarLengthOversea = this.data.indexListOversea.length;
            const touch = e.touches[0];
            console.log(touch.clientY, barToTopOversea);
            let index = Math.floor(
                (touch.clientY - barToTopOversea) / itemHeight
            );
            if (index < 0) {
                index = 0;
            } else if (index > sidebarLengthOversea - 1) {
                index = sidebarLengthOversea - 1;
            }
            this.scrollToAnchorOversea(index);
        }
    },
    onBarTouchStop(e) {
        if (e.currentTarget.dataset.oversea == '00') {
            this.setData({
                activeAnchorIndex: null,
            });
        } else if (e.currentTarget.dataset.oversea == '01') {
            this.setData({
                activeAnchorIndexOversea: null,
            });
        }
    },
    scrollToAnchor(index) {
        if (
            typeof index !== 'number' ||
            this.data.activeAnchorIndex === index
        ) {
            return;
        }
        this.setData({
            activeAnchorIndex: index,
        });

        let query = wx.createSelectorQuery();
        query.select(`.record-city-index${index}`).boundingClientRect();
        query.selectViewport().scrollOffset();

        query.exec((res) => {
            console.log(res);
            this.setData(
                {
                    scrollTop: scrollTopInside + res[0].top - switchBottom,
                },
                () => {
                    scrollTopInside =
                        scrollTopInside + res[0].top - switchBottom;
                    console.log(scrollTopInside);
                }
            );
        });
    },
    scrollToAnchorOversea(index) {
        if (
            typeof index !== 'number' ||
            this.data.activeAnchorIndexOversea === index
        ) {
            return;
        }
        this.setData({
            activeAnchorIndexOversea: index,
        });

        let query = wx.createSelectorQuery();
        query.select(`.record-city-index-oversea${index}`).boundingClientRect();
        query.selectViewport().scrollOffset();

        query.exec((res) => {
            console.log(res);
            this.setData(
                {
                    scrollTopOversea:
                        scrollTopInsideOversea + res[0].top - switchBottom,
                },
                () => {
                    scrollTopInsideOversea =
                        scrollTopInsideOversea + res[0].top - switchBottom;
                    console.log(scrollTopInsideOversea);
                }
            );
        });
    },
    onScroll(e) {
        // 监听滚动事件
        scrollTopInside = e.detail.scrollTop;
    },
    onScrollOversea(e) {
        // 监听滚动事件
        scrollTopInsideOversea = e.detail.scrollTop;
    },
    // 获取热门城市
    getHotCities(type, arrName) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'code/getHotCities',
            data: {
                oversea: type,
            },
            success(res) {
                _that.setData({
                    [arrName]: res.data.data,
                });
            },
        });
    },

    // 获取首字母城市列表
    getCityInitialList(type, objName, arrName, indexName, index) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'code/getCityInitialList',
            data: {
                oversea: type,
                listtype: _that.data.sortRulesArr[index].cityListType,
            },
            success(res) {
                if (res.data.status === '0') {
                    // 获取所有首字母数据，并将有数据的城市和索引放入相关的数组中
                    _that.setData(
                        {
                            [objName]: res.data.data,
                        },
                        () => {
                            // 定义一个暂时的空数组
                            let tempRecordCity = [];
                            let tempIndexList = [];
                            for (let key of Object.keys(_that.data[objName])) {
                                if (_that.data[objName][key].length > 0) {
                                    tempRecordCity.push(
                                        _that.data[objName][key]
                                    );
                                    tempIndexList.push(key);
                                }
                            }
                            tempRecordCity.forEach((arr) => {
                                arr.forEach((item) => {
                                    item.foreignName =
                                        item.enname &&
                                        (item.enname.split(',')[2] ||
                                            item.enname.split(',')[1]);
                                });
                            });
                            // 数据处理完成后再去获取对应元素的高度等数据
                            _that.setData(
                                {
                                    [arrName]: tempRecordCity,
                                    [indexName]: tempIndexList,
                                },
                                () => {
                                    _that.getElementData(type);
                                }
                            );
                        }
                    );
                }
            },
        });
    },

    // 获取相关元素高度等数据
    getElementData(type) {
        let query = wx.createSelectorQuery();
        query.select('.all-city').boundingClientRect();
        query.exec((res) => {
            switchBottom = res[0].bottom;
        });

        let queryCityBarItem = wx.createSelectorQuery();
        queryCityBarItem.select('.city-bar-item0').boundingClientRect();
        queryCityBarItem.exec((res) => {
            itemHeight = res[0].height;
        });

        if (type == '00') {
            let queryCityBar = wx.createSelectorQuery();
            queryCityBar.select('.city-bar-national').boundingClientRect();
            queryCityBar.exec((res) => {
                barToTop = res[0].top;
            });
        } else if (type == '01') {
            let queryCityBar = wx.createSelectorQuery();
            queryCityBar.select('.city-bar-oversea').boundingClientRect();
            queryCityBar.exec((res) => {
                barToTopOversea = res[0].top;
            });
        }
    },

    // 搜索城市
    searchCities(inputValue) {
        if (!inputValue) return;
        this.setData({
            searching: true,
        });
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'code/searchAllCity',
            data: {
                city: inputValue,
            },
            success(res) {
                if (res.data.status === '0') {
                    let matchCity = res.data.data;
                    matchCity.forEach((item) => {
                        item.nodes = `<span>${item.city}<span>`;
                        item.foreignName =
                            item.enname &&
                            (item.enname.split(',')[2] ||
                                item.enname.split(',')[1]);
                    });

                    if (_that.isAllChinese(_that.data.inputValue)) {
                        _that.strongMatchWord(
                            matchCity,
                            'nodes',
                            _that.data.inputValue
                        );
                    }

                    _that.setData({
                        matchCity: matchCity,
                        match: matchCity.length > 0,
                        searching: false,
                    });
                }
            },
        });
    },

    // 创建历史记录
    createCitySearchHistory(authId, city, country) {
        wx.request({
            url: app.globalData.rootPath + 'cjMap/createCitySearchHistory',
            data: {
                authId,
                city,
                country,
            },
            success(res) {
                console.log(res);
            },
        });
    },

    // 获取历史城市
    getCityHistory(authId, lat, lng, oversea) {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                'cjMap/getCitySearchHistoryListByParameter',
            data: {
                authId,
                oversea,
            },
            success(res) {
                let tempHistoryCityArr = [];
                // 先添加当前城市
                tempHistoryCityArr.unshift({
                    country: app.globalData.countryTap,
                    city: app.globalData.addressTap,
                    location: {
                        lat: lat,
                        lng: lng,
                    },
                });
                if (res.data.status === '0') {
                    _that.setData(
                        {
                            historyCityArr: res.data.data,
                        },
                        () => {
                            // 若当前城市在历史城市中，需要去掉
                            if (_that.data.historyCityArr.length > 0) {
                                for (
                                    let i = 0;
                                    i < _that.data.historyCityArr.length;
                                    i++
                                ) {
                                    if (
                                        _that.data.historyCityArr[i].city !=
                                        tempHistoryCityArr[0].city
                                    ) {
                                        tempHistoryCityArr.push(
                                            _that.data.historyCityArr[i]
                                        );
                                    }
                                }
                            }

                            _that.setData({
                                // 只要前六个
                                curAndHistoryArr: tempHistoryCityArr.slice(
                                    0,
                                    6
                                ),
                            });
                        }
                    );
                } else {
                    _that.setData({
                        // 只有当前城市
                        curAndHistoryArr: tempHistoryCityArr,
                    });
                }
            },
        });
    },
    // 获取历史城市
    getseaCityHistory(authId, lat, lng, oversea) {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                'cjMap/getCitySearchHistoryListByParameter',
            data: {
                authId,
                oversea,
            },
            success(res) {
                let tempHistoryCityArr = [];
                // 先添加当前城市
                tempHistoryCityArr.unshift({
                    country: app.globalData.countryTap,
                    city: app.globalData.addressTap,
                    location: {
                        lat: lat,
                        lng: lng,
                    },
                });
                if (res.data.status === '0') {
                    // 若当前城市在历史城市中，需要去掉
                    if (res.data.data.length > 0) {
                        for (let i = 0; i < res.data.data.length; i++) {
                            if (
                                res.data.data[i].city !=
                                tempHistoryCityArr[0].city
                            ) {
                                tempHistoryCityArr.push(res.data.data[i]);
                            }
                        }
                    }
                    _that.setData({
                        // 只要前六个
                        overseaAndHistoryArr: tempHistoryCityArr.slice(0, 6),
                    });
                } else {
                    _that.setData({
                        // 只有当前城市
                        overseaAndHistoryArr: tempHistoryCityArr,
                    });
                }
            },
        });
    },
    // 判断是否全是汉字，只有全是汉字才高亮
    isAllChinese(str) {
        let reg = /^[\u4E00-\u9FA5]+$/;
        if (!reg.test(str)) {
            return false;
        } else {
            return true;
        }
    },

    // 高亮搜索的字段
    strongMatchWord(matchCity, key, inputValue) {
        let wordArr = inputValue.split('');
        for (let i = 0; i < matchCity.length; i++) {
            for (let j = 0; j < wordArr.length; j++) {
                let reg = new RegExp('(' + wordArr[j] + ')', 'g');
                matchCity[i][key] = matchCity[i][key].replace(
                    reg,
                    "<font style='color:#00c7ff;'>$1</font>"
                );
            }
        }
    },

    changeNav: throttle((e) => {
        let { nav } = e.currentTarget.dataset;
        console.log(nav);
        if (
            app.globalData.authority == '07' ||
            app.globalData.authority == ''
        ) {
            wx.showToast({
                title: '尚未登录，不可以切换城市',
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 2000,
            });
            return;
        }
        wx.navigateTo({
            url: `${nav}`,
        });
    }, 200),

    // 改变排序规则
    changeSortRule(e) {
        let { oversea, index } = e.currentTarget.dataset;
        if (oversea) {
            this.setData({
                currentSortRuleIndexOversea: index,
            });
            this.getCityInitialList(
                '01',
                'allCityObjectOversea',
                'recordCityArrOversea',
                'indexListOversea',
                index
            );
        } else {
            this.setData({
                currentSortRuleIndex: index,
            });
            this.getCityInitialList(
                '00',
                'allCityObject',
                'recordCityArr',
                'indexList',
                index
            );
        }
    },

    // 获取我的城市
    getMyCity() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getCityByUid',
            data: {
                authId: app.globalData.authId,
            },
            success(res) {
                if (res.data.status === '0') {
                    _that.setData({
                        myCityCount: res.data.data.length,
                    });
                }
            },
        });
    },
});
